package com.bstek.bdf2.core.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;


/**
 * AuthenticationEntryPoint
 *
 * @since 2013-1-23
 * @author Jacky.gao
 */
public class MultiAuthenticationEntryPoint implements AuthenticationEntryPoint {
	private String authenticationType="form";
	/**
	 * 基于登录页面的认证方案入口，通过配置获取loginFormUrl（对应登录地址），当出现认证异常时，
	 * 会跳转到loginFormUrl对应的登录界面。
	 * 对应UsernamePasswordAuthenticationFilter过滤器类。
	 */
	private LoginUrlAuthenticationEntryPoint loginUrlAuthenticationEntryPoint;
	/**
	 * 将用户的浏览器重定向到CAS服务器
	 */
//	private CasAuthenticationEntryPoint casAuthenticationEntryPoint;
	/**
	 * 对应标准Http Basic认证流程的触发动作，向响应写入状态字401和头部WWW-Authenticate:"Basic realm="xxx"触发标准Http Basic认证流程。
	 * 对应BasicAuthenticationFilter过滤器。
	 */
	private BasicAuthenticationEntryPoint basicAuthenticationEntryPoint;
	/**
	 * 启动身份验证方案
	 * 实现应根据需要修改ServletResponse的标头以开始身份验证过程
	 */
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		if(authenticationType.equals("form")){
			loginUrlAuthenticationEntryPoint.commence(request, response, authException);
		} else if(authenticationType.equals("basic")){
			basicAuthenticationEntryPoint.commence(request, response, authException);
		}else{
			throw new IllegalArgumentException("Does not support current authentication type ["+authenticationType+"]");
		}
		
	}

	public void setLoginUrlAuthenticationEntryPoint(
			LoginUrlAuthenticationEntryPoint loginUrlAuthenticationEntryPoint) {
		this.loginUrlAuthenticationEntryPoint = loginUrlAuthenticationEntryPoint;
	}

//	public void setCasAuthenticationEntryPoint(
//			CasAuthenticationEntryPoint casAuthenticationEntryPoint) {
//		this.casAuthenticationEntryPoint = casAuthenticationEntryPoint;
//	}

	public void setBasicAuthenticationEntryPoint(
			BasicAuthenticationEntryPoint basicAuthenticationEntryPoint) {
		this.basicAuthenticationEntryPoint = basicAuthenticationEntryPoint;
	}

	public void setAuthenticationType(String authenticationType) {

		this.authenticationType = authenticationType;
	}
}